//
//  FirstViewController.m
//  NewsChannal
//
//  Created by chinabyte on 2017/7/18.
//  Copyright © 2017年 chinabyte. All rights reserved.
//

#import "FirstViewController.h"
#import "NewsChannelsView.h"
#import "ContentViewController.h"
#import "NewsChannelController.h"
#import "UIView+Extension.h"
#define NavigationBarHeight 64
@interface FirstViewController ()<UIScrollViewDelegate,NewsChannelsViewDelegate,NewsChannelControllerDelegate>
@property (nonatomic, strong) NewsChannelsView *channelsView;
//controller视图
@property (nonatomic, strong) UIScrollView * controllerScrollView;
//我的频道
@property (nonatomic, strong) NSMutableArray *myChannels;
//推荐频道
@property (nonatomic, strong) NSMutableArray *recommendChannels;
//子控制器数组
@property (nonatomic, strong) NSMutableArray *childControllers;
//当前选中的频道索引
@property (nonatomic, assign) NSInteger currentSelectedIndex;
@end

@implementation FirstViewController

- (NSMutableArray *)recommendChannels{
    if (!_recommendChannels) {
        _recommendChannels = [[NSMutableArray alloc]initWithArray:@[@"娱乐",@"北京",@"热点",@"问答",@"汽车",@"体育",@"财经",@"军事",@"段子",@"趣图",@"正能量",@"特写",@"中国新唱将",@"小说",@"房产",@"时尚",@"直播",@"历史",@"育儿"]];
    }
    return _recommendChannels;
}
- (NSMutableArray *)myChannels{
    if (_myChannels == nil) {
        _myChannels = [[NSMutableArray alloc]initWithArray:@[@"推荐",@"社会",@"图片",@"视频",@"国际",@"科技",@"健康",@"美女",@"科技头条",@"频道",@"美女图集"]];
    }
    return _myChannels;
}
- (NSMutableArray *)childControllers{
    if (!_childControllers) {
        _childControllers = [NSMutableArray array];
    }
    return _childControllers;
}

- (NewsChannelsView *)channelsView{
    if (!_channelsView) {
        _channelsView = [NewsChannelsView newsChannelsView];
        _channelsView.newsChannels = self.myChannels;
        _channelsView.ttDelegate = self;
    }
    return _channelsView;
}

- (UIScrollView *)controllerScrollView{
    if (_controllerScrollView == nil) {
        _controllerScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, NavigationBarHeight, CGRectGetWidth(self.view.frame), CGRectGetHeight(self.view.frame) - NavigationBarHeight)];
        _controllerScrollView.scrollEnabled=YES;
        _controllerScrollView.pagingEnabled = YES;
        _controllerScrollView.delegate = self;
        _controllerScrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
        _controllerScrollView.showsHorizontalScrollIndicator = NO;
        _controllerScrollView.backgroundColor = [UIColor yellowColor];
    }
    return _controllerScrollView;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    if ([self respondsToSelector:@selector(setEdgesForExtendedLayout:)]) {
        [self setEdgesForExtendedLayout:UIRectEdgeNone];
    }
    [self.view addSubview:self.channelsView];
    [self.view addSubview:self.controllerScrollView];
    [self setChildViewControllers];
    [self addChildVcView];
}
- (void)setChildViewControllers{
    for (int i = 0; i < self.myChannels.count; i++){
        ContentViewController * content = [[ContentViewController alloc]init];
        content.indexStr = [NSString stringWithFormat:@"测试%d",i];
        content.titleStr = self.myChannels[i];
        [self addChildViewController:content];
        [self.childControllers addObject:content];
    }
    self.controllerScrollView.contentSize = CGSizeMake(self.childControllers.count * self.controllerScrollView.frame.size.width, 0);
}

#pragma mark - 添加子控制器的view
- (void)addChildVcView
{
    NSUInteger index = self.controllerScrollView.contentOffset.x / self.controllerScrollView.frame.size.width;
    UIViewController *childVc = self.childControllers[index];
    if ([childVc isViewLoaded]) return;
    
    childVc.view.frame = self.controllerScrollView.bounds;
    [self.controllerScrollView addSubview:childVc.view];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    //根据滑动的效果实现头部标题栏的效果（标题文字效果）
    NSInteger currentIndex = (NSInteger)scrollView.contentOffset.x/scrollView.frame.size.width;
    NSInteger nextIndex = (scrollView.contentOffset.x > scrollView.frame.size.width * currentIndex) ? currentIndex+1:currentIndex-1;
    CGFloat rate_i = (scrollView.contentOffset.x - scrollView.frame.size.width * currentIndex)/scrollView.frame.size.width;
    [self.channelsView transformStatusWithCurrentIndex:currentIndex nextIndex:nextIndex withRate:rate_i];
}

-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    NSInteger currentIndex = (NSInteger)scrollView.contentOffset.x/scrollView.frame.size.width;
    [self.channelsView scrollerToCenterWithIndex:currentIndex];
    [self addChildVcView];
}
#pragma mark - TTNewsChannelsViewDelegate
- (void)NewsChannelsView:(NewsChannelsView *)newsChannelsView didSelectedNewsChannelItemAtIndex:(NSInteger)index{
    [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*index, 0) animated:NO];
    [self addChildVcView];
}

- (void)NewsChannelsView:(NewsChannelsView *)newsChannelsView didSelectedAddNewsChannelButton:(BOOL)selected{
    if (selected) {
        NewsChannelController *channelsVC = [NewsChannelController new];
        channelsVC.dataSource = @[self.myChannels,self.recommendChannels];
        channelsVC.currentIndex = self.channelsView.currentIndex;
        channelsVC.ttDelegate = self;
        channelsVC.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:channelsVC animated:YES];
    }
}
//选中某个频道后的回调
- (void)NewsChannelController:(NewsChannelController *)controller didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    [self.channelsView selectNewsChannelsItemWithIndex:indexPath.item];
}

- (void)NewsChannelController:(NewsChannelController *)controller didAddItemAtIndexPath:(NSIndexPath *)indexPath{
    //将新频道添加到我的频道末尾
    [self.myChannels addObject:self.recommendChannels[indexPath.item]];
    //从推荐数组中删除数据
    [self.recommendChannels removeObjectAtIndex:indexPath.item];
    //重新布局频道列表
    self.channelsView.newsChannels = self.myChannels;
    ContentViewController * content = [[ContentViewController alloc]init];
    content.indexStr = [NSString stringWithFormat:@"测试%lu",self.myChannels.count-1];
    content.titleStr = self.myChannels.lastObject;
    [self addChildViewController:content];
    [self.childControllers addObject:content];
    self.controllerScrollView.contentSize = CGSizeMake(self.childControllers.count * self.controllerScrollView.frame.size.width, 0);
}

- (void)NewsChannelController:(NewsChannelController *)controller didDeleteItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    NSString *deletedChannel = self.myChannels[sourceIndexPath.item];
    [self.myChannels removeObject:deletedChannel];
    [self.recommendChannels insertObject:deletedChannel atIndex:destinationIndexPath.item];
    UIViewController *childVC = (UIViewController *)self.childControllers[sourceIndexPath.item];
    if ([childVC isViewLoaded]) {
        [childVC.view removeFromSuperview];
    }
    [self.childControllers removeObject:childVC];
    [childVC removeFromParentViewController];
    self.controllerScrollView.contentSize = CGSizeMake(self.childControllers.count * self.controllerScrollView.frame.size.width, 0);
    for (NSInteger i = sourceIndexPath.item; i < self.childControllers.count; i++) {
        UIViewController *vc = self.childControllers[i];
        if ([vc isViewLoaded]) {
            vc.view.tt_x = i*self.controllerScrollView.frame.size.width;
        }
    }
    if (self.channelsView.currentIndex == sourceIndexPath.item) {
        //如果当先的频道被删除，则选中第一个频道
        self.channelsView.currentIndex = 0;
        [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*self.channelsView.currentIndex, 0) animated:NO];
    } else if (self.channelsView.currentIndex < sourceIndexPath.item){
        //如果删除的频道在当前频道的后面，只需要更新布局
    } else if (self.channelsView.currentIndex > sourceIndexPath.item){
        //如果删除的频道在当前频道的前面，需要将当前的频道索引-1
        self.channelsView.currentIndex -= 1;
        [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*self.channelsView.currentIndex, 0) animated:NO];
    }
    //重新布局频道列表
    self.channelsView.newsChannels = self.myChannels;
}

- (void)NewsChannelController:(NewsChannelController *)controller moveItemAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath{
    NSString *sourceChannel = self.myChannels[sourceIndexPath.item];
    [self.myChannels removeObject:sourceChannel];
    [self.myChannels insertObject:sourceChannel atIndex:destinationIndexPath.item];
    // 子控制器数组
    UIViewController *sourceVC = self.childControllers[sourceIndexPath.item];
    [self.childControllers removeObject:sourceVC];
    [self.childControllers insertObject:sourceVC atIndex:destinationIndexPath.item];
    // scrollerView的子view位置
    if ([sourceVC isViewLoaded]) {
        sourceVC.view.tt_x = destinationIndexPath.item * self.controllerScrollView.frame.size.width;
    }
    NSInteger currentIndex = self.channelsView.currentIndex;
    if (sourceIndexPath.item < destinationIndexPath.item) {
        // 往后挪
        for (NSInteger i = sourceIndexPath.item; i < destinationIndexPath.item; i++) {
            UIViewController *vc = self.childControllers[i];
            if ([vc isViewLoaded]) {
                vc.view.tt_x = i*self.controllerScrollView.frame.size.width;
            }
        }
        if (currentIndex == sourceIndexPath.item) {
            self.channelsView.currentIndex = destinationIndexPath.item;
            [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*self.channelsView.currentIndex, 0) animated:NO];
        } else if (currentIndex > sourceIndexPath.item && currentIndex <= destinationIndexPath.item){
            self.channelsView.currentIndex -= 1;
            [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*self.channelsView.currentIndex, 0) animated:NO];
        }
    } else {
        // 往前挪
        for (NSInteger i = destinationIndexPath.item + 1; i <= sourceIndexPath.item; i++) {
            UIViewController *vc = self.childControllers[i];
            if ([vc isViewLoaded]) {
                vc.view.tt_x = i*self.controllerScrollView.frame.size.width;
            }
        }
        if (currentIndex == sourceIndexPath.item) {
            self.channelsView.currentIndex = destinationIndexPath.item;
            [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*self.channelsView.currentIndex, 0) animated:NO];
        } else if (currentIndex >= destinationIndexPath.item && currentIndex < sourceIndexPath.item){
            self.channelsView.currentIndex += 1;
            [self.controllerScrollView setContentOffset:CGPointMake(self.controllerScrollView.frame.size.width*self.channelsView.currentIndex, 0) animated:NO];
        }
    }
    //重新布局频道列表
    self.channelsView.newsChannels = self.myChannels;
}

@end
